//
//  XGRichTextLabel.swift
//  Emoji
//
//  Created by monkey on 2020/3/4.
//  Copyright © 2020 itcast. All rights reserved.
//

import YYText

protocol XGRichTextLabelDelegate: AnyObject
{
    func richTextLabel(selectedText: String, type: XGRichTextType) -> Void
}

enum XGRichTextType
{
    /// 用户名
    case userName
    /// url地址
    case address
    /// 话题
    case topic
}

class XGRichTextLabel: YYLabel
{
    /// 代理
    weak var delegate: XGRichTextLabelDelegate?
    /// 超链接颜色
    var linkColor: UIColor = UIColor.orange
    /// 超链接背景色
    var linkBackgroundColor: UIColor = UIColor.lightGray
        
    // 覆盖父类属性的didset 并在里面重新赋值会造成死递归 解决办法super.属性名 = 新值
    override var attributedText: NSAttributedString? {
        didSet {
            if attributedText != nil {
                let attributedStringM = NSMutableAttributedString(attributedString: attributedText!)
                addAllLink(attributedStringM)
                super.attributedText = attributedStringM
            }
        }
    }
    
    // 覆盖父类属性的didset 并在里面重新赋值会造成死递归 解决办法super.属性名 = 新值
    override var text: String? {
        didSet {
            if text != nil {
                let attributedStringM = NSMutableAttributedString(string: text!, attributes: [.font: font  ,.foregroundColor: textColor])
                addAllLink(attributedStringM)
                super.attributedText = attributedStringM
            }
        }
    }
    
    private func addAllLink(_ attributedStringM: NSMutableAttributedString) -> Void
    {
        addLinkTextAction(pattern: "[a-zA-Z]*://[a-zA-Z0-9/\\.]*", attributedStringM: attributedStringM, type: .address)
        addLinkTextAction(pattern: "#.*?#", attributedStringM: attributedStringM, type: .topic)
        addLinkTextAction(pattern: "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*", attributedStringM: attributedStringM, type: .userName)
        attributedStringM.yy_lineSpacing = 5.0
    }
    
    private func addLinkTextAction(pattern: String, attributedStringM: NSMutableAttributedString, type: XGRichTextType) -> Void
    {
        let regularExpression = try! NSRegularExpression(pattern: pattern, options: [])
        let results = regularExpression.matches(in: attributedStringM.string, options: [], range: attributedStringM.yy_rangeOfAll())
        results.forEach { (result) in
            attributedStringM.yy_setTextHighlight(result.range, color: linkColor, backgroundColor: linkBackgroundColor) { [weak self] (_, _, range, _) in
                self?.delegate?.richTextLabel(selectedText: (attributedStringM.string as NSString).substring(with: range), type: type)
            }
        }
    }
}
